

JavaScriptManager = new MooTools.Class({

	Implements: [MooTools.Options, MooTools.Events],
	
	a: null, // hash to keep track of js files
	
	options : {
		baseUrl: 'http://localhost/~alihasan/acp/js/',
		mergeUrl: 'http://o.aolcdn.com/art/merge',
		mergeExp:31536000,
		mergeVer:16
	},
	
	initialize : function(options) {
		this.setOptions(options);
		this.a = new MooTools.Hash();
		window.addEvent('jsLoad', this.jsLoaded.bind(this)); // listens for jsLoad event and updates hash
	},
	
	// get js file name
	extract : function(url) {
		urlMatch = url.match(/\/([a-zA-Z0-9\-\_\.]*)$/);
		if (urlMatch !== null) {
			return urlMatch.getLast();
		}
		else {
			return url;
		}
	},
	
	// remove dots
	normalize : function(url) {
		return url.replace(/\./g,''); 
	},
	
	// clones
	clone : function(source) {
		target = {};
		for (el in source) {
			target[el] = source[el];
		}
		return target;
	},
	
	// updates has, calls com.aol.shared.JavaScriptLoader to load js files
	fetch : function(jsArray,fn,merge) {
		jsFetchArray = [];
		jsArray.each(function(url) {
			js = this.normalize(this.extract(url));
			// if js has never been requested
			if (!this.a.has(js)) {
				this.a.set(js,false);
				jsObj = {'js' : js, 'url' : url};
				jsFetchArray.push(jsObj);
			}
			// if js has been requested but has not loaded
			else if(!this.a.get(js)) {
				jsObj = {'js' : js, 'url' : null};
				jsFetchArray.push(jsObj);
			}
		}.bind(this));	

		//console.log(jsFetchArray);
		
		// if there are files to load
		if (jsFetchArray.length !== 0) {
			o = this.clone(this.options);
			o.jsArray = jsFetchArray;
			if($defined(fn)) {o.onJsComplete = fn};
			if($defined(merge)) {o.merge = merge};
			f = new JavaScriptLoader(o);
		}
		// if all files have been loaded 
		else if($defined(fn)){
			window.addEvent('jsComplete', fn);
			window.fireEvent('jsComplete', { status : true });
			window.removeEvent('jsComplete', fn);
		}
	},
	
	jsLoaded : function(e) {
		e_n = this.normalize(e);
		if (this.a.has(e_n) && !this.a.get(e_n)) {
			//console.log("MASTER: " + e + "... is loaded.")
			this.a.set(e_n,true);
		}
	}
});

JavaScriptLoader = new MooTools.Class({

	Implements: [MooTools.Options, MooTools.Events],

	d: null, // document
	h: null, // head
	a: null, // hash to keep track of js files
	c: false, // complete Flag
	
	options : {
		baseUrl: null,
		mergeUrl: null,
		mergeExp: null,
		mergeVer: null,
		merge: false, // to merge or not to merge
		jsArray: [], // js files to load
		onJsComplete: $empty // called when all js loading is complete
	},
	
	initialize : function(options) {
		this.setOptions(options);
		this.d = document;
		this.h = this.d.getElements('head')[0];
		this.a = new MooTools.Hash();
		window.addEvent('jsLoad', this.jsLoaded.bind(this));
		this.options.jsArray.each(function(jsObj) { this.build(jsObj) }.bind(this));
		if (this.options.merge) {
			this.jsMerge(this.options.jsArray);
		}
		else {
			this.options.jsArray.each(function(jsObj) { this.js(jsObj) }.bind(this));
		}
	},
	
	normalize : function(url) {
		return url.replace(/\./g,''); 
	},
	
	build : function(jsObj) {
		this.a.set(jsObj.js,false);
	},
	
	js : function(jsObj) {
		if (jsObj.url !== null) {
			if(jsObj.url.search(/http/i) > -1) {
				js = this.create(jsObj.url);
			}
			else {
                //console.log("jsObj.url: " + this.to_uri(jsObj.url))
//				js = this.create(this.options.baseUrl + jsObj.url);
                js = this.create("http://localhost:3000//javascripts/application/library/controls/TabControl/js/TabControl.js");
			}
		}		
	},
	
	jsMerge : function(jsArray) {
		mergedUrl = this.options.mergeUrl;
		jsArray.each(function(jsObj) {
			if (jsObj.url !== null) {
				if (mergedUrl.search(/\?/) === -1) { mergedUrl += "?f=/" + jsObj.url; }
				else {  mergedUrl += "&f=/" + jsObj.url; } 
			}
		});
		mergedUrl += "&expsec=" + this.options.mergeExp + "&ver=" + this.options.mergeVer;
		//console.log(mergedUrl);
		js = this.create(mergedUrl);
	},

	jsLoaded : function(e) {
		e_n = this.normalize(e);
		if (this.a.has(e_n) && !this.a.get(e_n)) {
			//console.log("     instance " + e + "... is loaded.")
			this.a.set(e_n,true);
			this.allLoadedCheck();
		}
	},
	
	allLoadedCheck : function() {
		complete = true;
		this.a.each(function(key) { 
			if(key === false) { 
				complete = false;
				return;
			}
		}.bind(this));
		if (complete) {
			this.complete = true;
			this.fireEvent('jsComplete', { status : this.complete });
		}
	},
	
	create : function(url) {
        console.log("url: " + url)
		//console.log('getting... ' + url)
		s = new Element('script');
		s.set('type','text/javascript');
		s.set('src',url);
		s.injectInside(this.h);
	},
    
    to_uri : function(namespc){
		var file_path, ns  = namespc;
		var isHttpath 	   = /^(http\:\/\/|\/)(.)+/;
		var isNamespace    = /\:{2}/;
		var isControl 	   = /controls/ig;
		if(ns && isNamespace.test(ns)) {
			var parts 	   = ns.split(isNamespace);
			var classname  = parts.pop();
			var path 	   = parts.join("/");
			
			if(parts[0].toLowerCase() == "controls") {
				file_path = config.loadpaths.CONTROLS.replace(/\[classname\]/ig, classname);
			}
			else{file_path = config.loadpaths.LIBROOT + path + "/" + classname + ".js";}	
		}
		else if(ns && isHttpath.test(ns)) { file_path = ns; }
		else {file_path = config.loadpaths.LIBROOT + ns + ".js";}
		
		//CACHING?
		file_path = (isHttpath.test(file_path)) ? 
			file_path : (cdn() + "/" + file_path);
		if(config.caching.enabled == false) {
			file_path = file_path + "?time=" + new Date().getTime();}
		return file_path;
	}
});